package com.pactera.service.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pactera.common.database.TargetDataSource;
import com.pactera.common.page.PageInfo;
import com.pactera.common.utils.UUIDUtils;
import com.pactera.mapper.MyUserMapper;
import com.pactera.mapper.SysUserMapper;
import com.pactera.model.MyUser;
import com.pactera.model.SysUser;

@Service
public class DynamicDataSourceService {

	private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceService.class);
	
	@Autowired
	private SysUserMapper tbSysUserMapper;
	
	@Autowired
	private MyUserMapper myUserMapper;
		
	@Transactional(readOnly=true)
	public List<SysUser> getSysUserListByDef() {
		List<SysUser> sysUserList = new ArrayList<>();
		LOGGER.info("####### mybatis-def-获取用户数据 #######");
		try {
			sysUserList = tbSysUserMapper.selectAll();
		} catch (Exception e) {
			LOGGER.error("获取异常",e);
		}
		return sysUserList;
	}
	
	@Transactional(readOnly=true)
	@TargetDataSource("ds1")
	public List<SysUser> getSysUserListByDs1() {
		List<SysUser> sysUserList = new ArrayList<>();
		LOGGER.info("####### mybatis-ds2-获取用户数据 #######");
		try {
			sysUserList = tbSysUserMapper.selectAll();
		} catch (Exception e) {
			LOGGER.error("获取异常",e);
		}
		return sysUserList;
	}
	
	@Transactional
	public boolean saveSysUserByDef(SysUser sysUser) {
		int cnt = 0 ;
		try {
			sysUser.setId(UUIDUtils.create());
			sysUser.setCreateTime(new Date());
			cnt = tbSysUserMapper.insert(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cnt > 0 ? true:false;
	}
	
	@Transactional(readOnly=true)
    public PageInfo<SysUser> getSysUserPageByDef(int currentPage,int pageSize) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        PageHelper.startPage(currentPage, pageSize);
        
        Page<SysUser> pageItems = tbSysUserMapper.selectAllByPage();
  
        PageInfo<SysUser> pageInfo = new PageInfo<>(pageItems);
        
        return pageInfo;
    }
	
	@Transactional(readOnly=true)
	@TargetDataSource("ds2")
	public PageInfo<MyUser> getSysUserPageByDs2(int currentPage,int pageSize) {
		//设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
		PageHelper.startPage(currentPage, pageSize);
		
		Page<MyUser> pageItems = myUserMapper.selectAllByPage();
		
		PageInfo<MyUser> pageInfo = new PageInfo<>(pageItems);
		
		return pageInfo;
	}
}
